import { Component, OnInit, ViewChild } from '@angular/core'
import {
  DialogService,
  FormLayout,
  TableWidthConfig,
  ToastService,
  LoadingService,
  DataTableComponent
} from 'ng-devui'
import { ManageService } from 'src/app/@core/manage.service'
import { CollectionDialogComponent } from './collection-dialog/collection-dialog.component'
import { DrawerService, IDrawerOpenResult } from 'ng-devui/drawer'
import { OperationConsoleComponent } from './operation-console/operation-console.component'
import { AuthGuardService } from 'src/app/@core/auth-guard-service.guard'

@Component({
  selector: 'app-collection',
  templateUrl: './collection.component.html',
  styleUrls: ['./collection.component.scss']
})
export class CollectionComponent implements OnInit {
  @ViewChild('dialog-service') dialogData: any
  @ViewChild(DataTableComponent, { static: true }) datatable: DataTableComponent
  iconParentOpen = '<span class="icon icon-chevron-right"></span>'
  iconParentClose = '<span class="icon icon-chevron-down"></span>'
  layoutDirection: FormLayout = FormLayout.Horizontal
  userId = parseInt(localStorage.getItem('userId'))

  queryParams = {
    userId: this.userId,
    page: 1,
    pageSize: 10,
    collectionIndex: null,
    collectionStatus: -1,
    collectionSymbol: null,
    collectionName: null
  }

  total = 0
  pageSizeOptions = [10, 20, 30, 40, 50]

  datas2 = {
    subCollectionIndex: null,
    collectionIndex: null,
    collectionName: null,
    saleTime: null,
    offShelfTime: null,
    price: null,
    userId: this.userId
  }

  status = ['', '未铸造', '铸造中', '铸造完成', '已发布', '出售中', '已结束', '销毁中']

  options2 = [
    {
      name: '未铸造',
      value: '1'
    },
    {
      name: '铸造中',
      value: '2'
    },
    {
      name: '铸造完成',
      value: '3'
    },
    {
      name: '已发布',
      value: '4'
    },
    {
      name: '出售中',
      value: '5'
    },
    {
      name: '已结束',
      value: '6'
    },
    {
      name: '销毁中',
      value: '7'
    }
  ]
  currentOption4 = { value: -1 }

  basicDataSource = [];

  dataTableOptions = {
    columns: [
      {
        field: 'url',
        header: '',
      },
      {
        field: 'collectionName',
        header: '藏品分类',
        fieldType: 'text'
      },
      {
        field: 'supplies',
        header: '总资产',
        fieldType: 'text'
      },
      {
        field: 'counters',
        header: '已领取资产',
        fieldType: 'text'
      },
      {
        field: 'saleTime',
        header: '发售开始时间',
        fieldType: 'text'
      },
      {
        field: 'offShelfTime',
        header: '发售结束时间',
        fieldType: 'text'
      },
      {
        field: 'price',
        header: '价格',
        fieldType: 'text'
      },
      {
        field: 'collectionStatus',
        header: '藏品状态',
        fieldType: 'text'
      },
      {
        field: 'op',
        header: '操作'
      }
    ]
  }

  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'url',
      width: '3%',
    },
    {
      field: 'collectionName',
      width: '15%',
    },
    {
      field: 'supplies',
      width: '10%',
    },
    {
      field: 'counters',
      width: '10%',
    },
    {
      field: 'saleTime',
      width: '13%',
    },
    {
      field: 'offShelfTime',
      width: '13%',
    },
    {
      field: 'price',
      width: '10%',
    },
    {
      field: 'collectionStatus',
      width: '11%',
    },
    {
      field: 'op',
      width: '15%'
    }
  ]

  private showLoading: any

  constructor(
    private dialogService: DialogService,
    private manageService: ManageService,
    private toastService: ToastService,
    private loadingService: LoadingService,
    private drawerService: DrawerService,
    private authGuardService: AuthGuardService
  ) { }

  ngOnInit(): void {
    if (localStorage.getItem('PasswordChange') == 'true') {
      this.getList()
    }
  }

  onChildTableToggle(status, rowItem) {
    this.datatable.setRowChildToggleStatus(rowItem, status)
  }

  refresh() {
    this.getList()
  }

  pageSizeChange(pageSize) {
    this.queryParams.pageSize = pageSize
    this.pageIndexChange(1)
  }

  pageIndexChange(pageIndex) {
    this.queryParams.page = pageIndex
    this.getList()
  }

  getList() {
    this.basicDataSource = []
    if (this.currentOption4) {
      this.queryParams.collectionStatus = this.currentOption4.value
    }
    var nowtime = -28800000
    this.manageService.collectionQuery(this.queryParams).subscribe((res) => {
      if (res.code == 0 && res.data.collections !== null) {
        res.data.collections.forEach((item) => {
          this.getTreeData(item)
        })
      }
      this.total = res.data.totalNum
    })
  }

  getTreeData(item) {
    var nowtime = -28800000
    item.subCollections.forEach((sub) => {
      sub.saleTime = sub.saleTime == nowtime ? "-" : this.timeTransform(sub.saleTime)
      sub.offShelfTime = sub.offShelfTime == nowtime ? "-" : this.timeTransform(sub.offShelfTime)
      sub.price = sub.price < 0 ? "-" : "￥" + parseFloat(sub.price).toFixed(2)
      sub.status = sub.collectionStatus
      sub.collectionStatus = this.status[sub.collectionStatus]
    })
    var collection = item.subCollections[0]
    var i
    if (item.subCollectionSize > 1) {
      collection.children = []
    }
    for (i = 1; i < item.subCollectionSize; i++) {
      collection.children.push(item.subCollections[i])
    }
    collection.$isChildTableOpen = true
    this.basicDataSource.push(collection)
  }

  timeTransform(time) {
    var date = new Date(time)
    var Y = date.getFullYear() + '-'
    var M =
      (date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1) + "-";
    var D =
      (date.getDate() < 10
        ? "0" + (date.getDate())
        : date.getDate()) + " ";

    var h = date.getHours() > 9 ? date.getHours() : "0" + date.getHours();
    var m = date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes();
    var s = date.getSeconds() > 9 ? date.getSeconds() : "0" + date.getSeconds();
    return Y + M + D + h + ":" + m + ":" + s;
  }

  openStandardDialog() {
    const results = this.dialogService.open({
      id: 'dialog-service',
      width: '600px',
      maxHeight: '600px',
      title: '新建藏品分类',
      content: CollectionDialogComponent,
      backdropCloseable: true,
      buttons: [
        {
          cssClass: 'primary',
          text: '确定',
          disabled: true,
          handler: ($event: Event) => {
            this.datas2.collectionIndex = results.modalContentInstance.branch
            this.datas2.collectionName =
              results.modalContentInstance.collectionName
            this.newCollection(results)
          }
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide()
          }
        }
      ],
      data: {
        canConfirm: (value: boolean) => {
          results.modalInstance.updateButtonOptions([{ disabled: !value }])
        }
      }
    })
  }

  newCollection(results) {
    this.showLoading = this.loadingService.open({
      message: '正在新建集合，请稍等……'
    })
    this.manageService.collectionAdd(this.datas2.collectionName, this.userId).subscribe(
      (res) => {
        this.showLoading.loadingInstance.close()
        if (res.code === 0) {
          this.toastService.open({
            value: [
              {
                severity: 'success',
                summary: '',
                content: '新建成功'
              }
            ]
          })
        }
        else {
          this.toastService.open({
            value: [
              {
                severity: 'error',
                summary: '',
                content: res.msg
              }
            ]
          })
        }
        results.modalInstance.hide()
        this.getList()
      },
      (err) => {
        this.showLoading.loadingInstance.close()
      }
    )
  }

  openPublishDialog(collectionIndex: string, subCollectionIndex: string, type: string) {
    const results = this.dialogService.open({
      title: '提示',
      dialogtype: 'warning',
      content: type == '取消发布' ? '是否取消发布？' : '销毁操作不可撤销，请确认是否销毁该集合？',
      buttons: [
        {
          cssClass: 'primary',
          text: '确认',
          handler: ($event: Event) => {
            if (type == '取消发布') {
              this.cancelPublish(collectionIndex, subCollectionIndex, results)
            }
            else {
              this.burn(collectionIndex, subCollectionIndex, results)
            }
          }
        },
        {
          cssClass: 'primary',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide()
          }
        }
      ]
    })
  }

  cancelPublish(collectionIndex, subCollectionIndex: string, results) {
    this.showLoading = this.loadingService.open({
      message: '正在取消发布，请稍等……'
    })
    this.datas2.collectionIndex = collectionIndex
    this.datas2.subCollectionIndex = subCollectionIndex
    this.manageService
      .collectionPublish(this.datas2)
      .subscribe((res) => {
        results.modalInstance.hide()
        if (res.code == 0) {
          this.showLoading.loadingInstance.close()
          this.getList()
          this.authGuardService.showModalPanel('success', res.msg)
        }
        else {
          this.authGuardService.showModalPanel('failed', res.msg)
        }
      })
  }

  burn(collectionIndex, subCollectionIndex, results) {
    this.showLoading = this.loadingService.open({
      message: '正在销毁集合，请稍等……'
    })
    this.manageService.collectionBurn(this.userId, collectionIndex, subCollectionIndex).subscribe((res) => {
      this.showLoading.loadingInstance.close()
      results.modalInstance.hide()
      if (res.code == 0) {
        this.getList()
        this.authGuardService.showModalPanel('success', res.msg)
      }
      else {
        this.authGuardService.showModalPanel('failed', res.msg)
      }
    })
  }

  restForm() {
    this.currentOption4 = { value: -1 }
    this.queryParams = {
      userId: this.userId,
      page: 1,
      pageSize: this.queryParams.pageSize,
      collectionIndex: null,
      collectionName: null,
      collectionSymbol: null,
      collectionStatus: null
    }
    this.getList()
  }

  submitForm(term) {
    if (this.currentOption4 === null) {
      this.currentOption4 = { value: -1 }
    }
    this.queryParams.collectionStatus = this.currentOption4.value
    this.queryParams.page = 1
    this.getList()
  }

  minting(state: number, type: string) {
    if (type == '铸造' && state == 2) return true
    if (type == '发布' && state == 3) return true
    if (type == '修改' && state < 4 && state != 2) return true
    if (type == '取消发布' && state > 3 && state < 7) return true
    if (type == '销毁' && state == 3) return true
    return false
  }

  results: IDrawerOpenResult

  openDrawer(collectionName: string, collectionIndex: string, subCollectionIndex: string, operate: string) {
    this.results = this.drawerService.open({
      drawerContentComponent: OperationConsoleComponent,
      width: '31.25%',
      zIndex: 1000,
      isCover: true,
      fullScreen: true,
      backdropCloseable: true,
      escKeyCloseable: true,
      position: 'right',
      bodyScrollable: true,
      beforeHidden: () =>
        this.beforeHidden(
          this.results.drawerContentInstance.formChange(),
          this.results.drawerContentInstance.prepare()
        ),
      data: {
        operate,
        collectionName,
        collectionIndex,
        subCollectionIndex,
        close: (event) => {
          this.results.drawerInstance.hide()
          this.getList()
        },
        closeDirectly: (event) => {
          this.results.drawerInstance.hideDirectly()
          this.getList()
        }
      }
    })
  }

  beforeHidden(isChange, prepare): Promise<boolean> {
    return new Promise((resolve) => {
      if (isChange) {
        const results = this.dialogService.open({
          id: 'dialog-service',
          width: '300px',
          zIndex: 1050,
          maxHeight: '600px',
          title: '温馨提示',
          content: '您修改了藏品信息，请问是否退出？',
          backdropCloseable: false,
          dialogtype: 'warning',
          buttons: [
            {
              cssClass: 'primary',
              text: '否',
              handler: ($event: Event) => {
                results.modalInstance.hide();
                resolve(false);
              }
            },
            {
              id: 'btn-cancel',
              cssClass: 'common',
              text: '是',
              handler: ($event: Event) => {
                results.modalInstance.hide();
                resolve(true);
              }
            }
          ]
        })
      } else {
        resolve(true);
      }
    })
  }
}
